import { constantRoutes, asyncRoutes } from '@/router'
import { tranListToTreeData } from '@/utils/index'
export default {
  namespaced: true,
  state() {
    return {
      routes: [...constantRoutes]
    }
  },
  mutations: {
    setRoute(state, data) {
      state.routes = [...constantRoutes, ...data]
    }
  },
  getters: {},
  actions: {
    // 思路一
    routesFilter(ctx, routerMarks) {
      const userAsyncRoutes = []
      asyncRoutes.forEach(item => {
        if (routerMarks.find(obj => obj.mark === item.name)) {
          if (item.children && item.children.length) {
            const temp = item.children.filter(val => {
              return routerMarks.find(o => o.mark === val.name)
            })
            item.children = temp
          }
          userAsyncRoutes.push(item)
        }
      })
      userAsyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
      ctx.commit('setRoute', userAsyncRoutes)
      return userAsyncRoutes
    },
    // 思路二
    generateRoutes(ctx, routerMarks) {
      let userAsyncRoutes = []
      routerMarks.forEach(item => {
        const obj = {}
        obj.meta = {
          title: item.title,
          icon: item.icon
        }
        obj.hidden = item.is_show !== 1
        obj.path = item.path
        if (item.component === 'layout') {
          obj.component = require('@/layout/index.vue').default
        } else {
          obj.component = require('@/views/' + item.component + '.vue').default
        }
        obj.id = item.id
        obj.pid = item.pid
        userAsyncRoutes.push(obj)
      })
      userAsyncRoutes = tranListToTreeData(userAsyncRoutes, 0)
      // console.log(userAsyncRoutes)
      ctx.commit('setRoute', userAsyncRoutes)
      return userAsyncRoutes
    }
  }
}
